<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.8/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <div>
            <h3>商品</h3>
            <div v-for="item in community" :key="community.id">
                名称：{{item.name}} / 价格：{{item.price}}
                <button @click="add(item)">添加</button>
            </div>
        </div>
        <div>
            <h3>购物车</h3> ---总价：{{total}}
            <div v-for="item,index in cart" :key="cart.id">
                名称：{{item.name}} ----价格：{{item.price}}
                ----数量{{item?.sum}}

                <button @click="remove(index)">删除</button>
            </div>
        </div>
    </div>
    <script>
        new Vue({
            el: "#app",
            data() {
                return {
                    community: [
                        { id: 1, name: '商品A', price: 100 },
                        { id: 2, name: '商品B', price: 200 },
                        { id: 3, name: '商品C', price: 300 },
                        { id: 4, name: '商品d', price: 300 },
                        { id: 5, name: '商品e', price: 300 },
                        { id: 6, name: '商品f', price: 300 },
                    ],
                    cart: []
                };
            },
            computed: {
                total() {
                    // reduce((上一次累加的值, 累加的每一项)=>{},初始值
                    return this.cart.reduce((to, item) => to + item.price * item.sum, 0)
                }
            },
            methods: {
                add(item) {
                    // 筛选出点击重复的每一项
                    let cartArr = this.cart.find((items, index) => item.id == items.id)
                    // 如果是第一次点击就直接添加到新数组里
                    if (!cartArr) {
                        this.cart.push({ ...item, sum: 1 })
                    } else {
                        // 如果是重复点击，则给cartArr对象添加一个计算加了多少次的属性用于记录
                        cartArr.sum++
                    }
                },
                remove(i) {
                    // 商品数量大于1时在购物车展示
                    if (this.cart[i].sum > 1) {
                        this.cart[i].sum--
                        return
                    }
                    // 当购物车数量为零时移除对象
                    this.cart.splice(i, 1)
                }
            }
        });
    </script>
</body>

</html>